
import Axios from 'axios';
import Vue from "vue";

import { Loading } from 'element-ui';
import da from "element-ui/src/locale/lang/da";

class Request {

  constructor(config){

    this._request = Axios.create(config);

    this._request.interceptors.request.use(config=>{

      config.headers.authorization = sessionStorage.getItem('token');
      this._loading = Loading.service({
          fullscreen:true,
          background: 'rgba(0, 0, 0, 0.7)'
        });
      return config;
    });

    this._request.interceptors.response.use(data=>{

      setTimeout(()=>{
        this._loading.close();
      },1);
      return data.data;
    })

  }


  _baseRequest(method,config){

    config['method'] = method;
    return this._request.request(config);
  }

  getRequest(config){
    return  new Promise((resolve, reject) => {

      this._baseRequest('get',config).then(data=>{

        if (data.code == 0){

          resolve(data.data);
          return;
        }

        if (data.code === 103){

          //token 过期
          sessionStorage.removeItem('token');
          //通知跳转到登录界面
          Vue.prototype.$bus.$emit('tokenExpire');
        }

        Vue.prototype.$message({
          showClose:true,
          message: data.msg,
          type:'error'
        });
        reject(data.msg);
      }).catch(error=>{

        reject(error);
      });
    });

  }

  postRequest(config){

   return  new Promise((resolve, reject) => {

      this._baseRequest('post',config).then(data=>{

        if (data.code == 0){

          resolve(data.data);
          return;
        }

        Vue.prototype.$message({
          showClose:true,
          message: data.msg,
          type:'error'
        });
        reject(data.msg);
      }).catch(error=>{

          reject(error);
      });
    })
  }
}

export const requestInstance = new Request({
  baseURL:'http://47.99.51.246:8081/admin/',
  timeout:30000
});


